/**
 * 强制连接重定向到HTTPS
 * 参考 https-redirect-server 
 **/

var createRedirectURL = function(hostname, url, securePort) {
	var secureHostname;

	if (securePort === 443) {
		secureHostname = hostname;
	} else { // host.com -> host.com:securePort
		secureHostname = hostname + ':' + securePort;
	}

	return 'https://' + secureHostname + url;
};

exports.forceSecure = function(securePort) {
	return function(req, res, next) {
		if (req.secure) {
			// 直接return否则会循环重定向
			return next();
		}
		// 支持Express3.x req.host & Express 4.x req.hostname
		var _hostname = req.hostname || req.host;
		var redirectURL = createRedirectURL(_hostname, req.originalUrl, securePort);
		res.redirect(redirectURL);
	};
};